﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ComLib.ComType;
using DataTransferClient;
using IUploading;
using LogLib;

namespace KWindow.KPageCore
{
    public class TransferControl : IDisposable
    {
        /// <summary>
        /// 请求上传数据的接口名称
        /// </summary>
        private string _interfaceName = "";

        private string _error = "";
        public string Error
        {
            get { return _error; }
        }

        private TransferClient _client = new TransferClient();

        #region To do something(delegate) after receive response from DeviceManageServer
        public DoSomething OnLoginOK { get; set; }
        public DoSomething OnLoginFailed { get; set; }
        public DoSomething OnLogoutOK { get; set; }
        public DoSomething OnLogoutFailed { get; set; }
        public DoSomething OnQueryOK { get; set; }
        public DoSomething OnQueryFailed { get; set; }
        public DoSomething OnPostOK { get; set; }
        public DoSomething OnPostFailed { get; set; }
        public DoSomething OnTestOK { get; set; }
        public DoSomething OnTestFailed { get; set; }
        public DoSomething OnTimeout { get; set; }
        public DoSomething OnCatchException { get; set; }
        #endregion

        public TransferControl(string name)
        {
            _interfaceName = name;
            InitDelegateFuncs();
        }

        /// <summary>
        /// 初始化所有的委托方法的对象
        /// 如果预测要使用该方法，必须在外部对其重新赋值
        /// </summary>
        private void InitDelegateFuncs()
        {
            // 以下委托必须在外部实现          
            OnPostOK = OnNotImplemented;
            OnPostFailed = OnNotImplemented;
            OnCatchException = OnNotImplemented;

            // 如果没有调用相关动作，以下委托可以不实现，
            // 但是如果有调用相关动作，必须实现对应动作请求返回后的回调
            // 否则将抛出异常
            OnLoginOK = OnNotImplemented;
            OnLoginFailed = OnNotImplemented;
            OnQueryOK = OnDefaultAction;
            OnQueryFailed = OnDefaultAction;
            OnTestFailed = OnDefaultAction;
            OnTestOK = OnDefaultAction;
            OnTimeout = OnDefaultAction;         
        }

        private void OnDefaultAction(string outstring)
        {

        }

        private void OnNotImplemented(string delegateFunName)
        {
            throw new NotImplementedException();
        }

        public bool Init()
        {
            _client.ConnectToServer();
            if (_client.Connected)
            {
                _client.ClientPackageReceived += NewPackage_Received;
                _client.ErrorReported += ClientError_Reported;
                Log.WriteAsync("客户端连接成功!");
                return true;
            }
            else
            {
                Log.WriteAsync("客户端连接失败!");
                return false;
            }
        }

        public void Exit()
        {

            Dispose();
        }

        private void ClientError_Reported(object sender, ErrorReportedEventArgs e)
        {
            _error = "客户端连接发生了异常: " + e.Message;
            Log.WriteAsync(_error);
        }

        private void NewPackage_Received(object sender, TransferClientPackageReceivedEventArgs e)
        {
            _error = "";
            TransferResponsePackge package = e.Package;
            TransferResult state = package.Result;
            string outParams = package.OutParams;
            string errorMsg = package.Message;
            switch (state)
            {
                case TransferResult.LoginOK:
                    OnLoginOK(outParams);
                    break;
                case TransferResult.LoginFailed:
                    OnLoginFailed(errorMsg);
                    break;
                case TransferResult.LogoutOK:
                    OnLogoutOK(outParams);
                    break;
                case TransferResult.LogoutFailed:
                    OnLogoutFailed(errorMsg);
                    break;
                case TransferResult.PostOK:
                    OnPostOK(outParams);
                    break;
                case TransferResult.PostFailed:
                    OnPostFailed(errorMsg);
                    break;
                case TransferResult.QueryOK:
                    OnQueryOK(outParams);
                    break;
                case TransferResult.QueryFailed:
                    OnQueryFailed(errorMsg);
                    break;
                case TransferResult.TestOK:
                    OnTestOK(outParams);
                    break;
                case TransferResult.TestFailed:
                    OnTestFailed(errorMsg);
                    break;
                case TransferResult.Timeout:
                    OnTimeout(errorMsg);
                    break;
                case TransferResult.CatchException:
                    OnCatchException(errorMsg);
                    break;
                default:
                    break;
            }
        }

        #region Data Transfer general controls 数据上传（传输）的基本操作

        /// <summary>
        /// 执行接口的基本操作之一: 登录，登出，测试，上传，查询
        /// </summary>
        /// <param name="action"></param>
        /// <param name="inParams"></param>
        protected void TakeAction(string action, string inParams)
        {
            if (!_client.Connected)
            {
                return;
            }
            TransferDataPackge pack = new TransferDataPackge();
            pack.InterfaceName = _interfaceName;
            pack.Action = action;
            pack.InParams = inParams;
            _client.SendRequest(pack);
        }

        /// <summary>
        ///  请求接口执行登录操作
        /// </summary>    
        /// <param name="inParams">请求登录需要输入的参数</param>
        public void Login(string inParams = "")
        {
            TakeAction(TransferAction.Login, inParams);
        }

        /// <summary>
        ///  请求接口执行登出操作
        /// </summary>
        /// <param name="inParams">请求控制需要输入的参数</param>
        public void Logout(string inParams = "")
        {
            TakeAction(TransferAction.Logout, inParams);
        }

        /// <summary>
        /// 请求接口执行上传数据操作(one motion)
        /// </summary>
        /// <param name="deviceName"></param>
        /// <param name="inParams"></param>
        public void Post(string inParams = "")
        {
            TakeAction(TransferAction.Post, inParams);
        }

        /// <summary>
        /// 请求接口执行上传数据操作(one motion)
        /// </summary>
        /// <param name="deviceName"></param>
        /// <param name="inParams"></param>
        public void PostAll(string inParams = "")
        {
            TakeAction(TransferAction.PostAll, inParams);
        }

        /// <summary>
        /// 请求接口执行测试功能
        /// </summary>
        /// <param name="inParams">输入参数</param>
        public void Test(string inParams = "")
        {
            TakeAction(TransferAction.Test, inParams);
        }

        /// <summary>
        /// 请求接口执行查询操作
        /// </summary>
        /// <param name="inParams">输入参数</param>
        public void Query(string inParams = "")
        {
            TakeAction(TransferAction.Query, inParams);
        }

        /// <summary>
        /// 请求关闭服务器操作
        /// </summary>
        /// <param name="inParams">输入参数</param>
        public void ExitApp(string inParams = "")
        {
            TakeAction(TransferAction.ExitApp, inParams);
        }

        #endregion

        public void Dispose()
        {
            _client.Close();
        }
    }
}
